// TogetherWatch - 视频同步功能库
(function (window) {
    class TogetherWatch {
        constructor(options = {}) {
            // WebSocket服务器地址
            this.wsServer = options.wsServer || 'ws://localhost:8080';

            // 当前房间ID
            this.roomId = null;

            // WebSocket连接
            this.socket = null;

            // 当前视频元素
            this.videoElement = null;

            // 是否是房主
            this.isHost = false;

            // 当前视频信息
            this.currentVideoInfo = {
                src: '',
                currentTime: 0,
                paused: true,
                playbackRate: 1
            };

            // 初始化UI元素
            this.initUI();

            // 绑定事件处理器
            this.bindEvents();
        }

        // 初始化悬浮按钮和弹窗
        initUI() {
            // 创建悬浮按钮
            this.floatButton = document.createElement('div');
            this.floatButton.innerHTML = '一起看';
            this.floatButton.style.cssText = `
                position: fixed;
                bottom: 20px;
                right: 20px;
                background-color: #4CAF50;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                cursor: pointer;
                z-index: 9999;
            `;

            // 创建弹窗
            this.modalOverlay = document.createElement('div');
            this.modalOverlay.style.cssText = `
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.5);
                z-index: 10000;
                justify-content: center;
                align-items: center;
            `;

            this.modalContent = document.createElement('div');
            this.modalContent.style.cssText = `
                background-color: white;
                padding: 20px;
                border-radius: 10px;
                width: 300px;
            `;

            this.modalContent.innerHTML = `
                <h2>一起看</h2>
                <div>
                    <input type="text" id="roomInput" placeholder="房间号">
                    <button id="joinRoomBtn">加入房间</button>
                    <button id="createRoomBtn">创建房间</button>
                    <p id="roomStatus"></p>
                </div>
            `;

            this.modalOverlay.appendChild(this.modalContent);

            document.body.appendChild(this.floatButton);
            document.body.appendChild(this.modalOverlay);
        }

        // 绑定事件
        bindEvents() {
            // 悬浮按钮点击事件
            this.floatButton.addEventListener('click', () => {
                this.modalOverlay.style.display = 'flex';
            });

            // 关闭弹窗点击事件
            this.modalOverlay.addEventListener('click', (e) => {
                if (e.target === this.modalOverlay) {
                    this.modalOverlay.style.display = 'none';
                }
            });

            // 加入房间按钮
            document.getElementById('joinRoomBtn').addEventListener('click', () => {
                const roomId = document.getElementById('roomInput').value.trim();
                if (roomId) {
                    this.joinRoom(roomId);
                }
            });

            // 创建房间按钮
            document.getElementById('createRoomBtn').addEventListener('click', () => {
                this.createRoom();
            });
        }

        // 连接WebSocket服务器
        connectWebSocket() {
            this.socket = new WebSocket(this.wsServer);

            this.socket.onopen = () => {
                console.log('WebSocket连接成功');

                // 如果是房主，发送创建房间消息
                if (this.isHost) {
                    this.socket.send(JSON.stringify({
                        type: 'create_room',
                        roomId: this.roomId
                    }));
                } else {
                    // 如果是成员，发送加入房间消息
                    this.socket.send(JSON.stringify({
                        type: 'join_room',
                        roomId: this.roomId
                    }));
                }
            };

            this.socket.onmessage = (event) => {
                const data = JSON.parse(event.data);
                this.handleWebSocketMessage(data);
            };
        }

        // 处理WebSocket消息
        handleWebSocketMessage(data) {
            switch (data.type) {
                case 'sync_video':
                    this.syncVideo(data);
                    break;
                case 'room_joined':
                    this.onRoomJoined(data);
                    break;
                case 'request_video_status':
                    this.sendVideoStatus();
                    break;
                case 'current_video_status':
                    this.applyReceivedVideoStatus(data);
                    break;
                case 'error':
                    this.handleError(data.message);
                    break;
            }
        }

        // 创建房间
        createRoom() {
            this.isHost = true;
            this.roomId = this.generateRoomId();
            document.getElementById('roomInput').value = this.roomId;
            this.setupVideoSync();
        }

        // 加入房间
        joinRoom(roomId) {
            this.isHost = false;
            this.roomId = roomId;
            this.setupVideoSync();
        }

        // 设置视频同步
        setupVideoSync() {
            // 连接WebSocket
            this.connectWebSocket();

            // 如果是房主，定期检查并同步视频状态
            if (this.isHost) {
                this.setupHostVideoTracking();
            } else {
                // 如果是成员，请求当前视频状态
                this.requestCurrentVideoStatus();
            }
        }

        // 房主视频状态追踪
        setupHostVideoTracking() {
            // 定时检查页面上的视频元素
            this.hostVideoCheckInterval = setInterval(() => {
                const video = this.findVideoElement();

                if (video && video !== this.videoElement) {
                    // 找到新的视频元素
                    this.videoElement = video;
                    this.attachVideoListeners();
                    this.sendVideoStatus();
                }
            }, 1000);
        }

        // 查找页面上的视频元素
        findVideoElement() {
            // 支持多种视频标签选择
            const videoSelectors = [
                'video',  // HTML5视频标签
                'iframe[src*="youtube.com"]',  // YouTube iframe
                'iframe[src*="bilibili.com"]',  // Bilibili iframe
                'iframe[src*="iqiyi.com"]',    // 爱奇艺iframe
                // 可以根据需要添加更多选择器
            ];

            for (let selector of videoSelectors) {
                const element = document.querySelector(selector);
                if (element) {
                    // 对于iframe，需要特殊处理
                    if (selector.includes('iframe')) {
                        return this.wrapIframeAsVideo(element);
                    }
                    return element;
                }
            }

            return null;
        }

        // 将iframe视频包装为类似video的对象
        wrapIframeAsVideo(iframe) {
            return {
                // 模拟video对象的关键方法和属性
                play: () => {
                    iframe.contentWindow.postMessage('play', '*');
                },
                pause: () => {
                    iframe.contentWindow.postMessage('pause', '*');
                },
                get paused() {
                    // 这里可能需要与iframe通信获取准确状态
                    return false;
                },
                get currentTime() {
                    // 需要与iframe通信获取当前时间
                    return 0;
                },
                set currentTime(time) {
                    iframe.contentWindow.postMessage({ type: 'seekTo', time }, '*');
                },
                get src() {
                    return iframe.src;
                },
                get playbackRate() {
                    return 1;
                },
                set playbackRate(rate) {
                    iframe.contentWindow.postMessage({ type: 'setPlaybackRate', rate }, '*');
                }
            };
        }

        // 绑定视频事件监听器
        attachVideoListeners() {
            if (!this.videoElement) return;

            // 移除旧的监听器
            if (this.videoEventListeners) {
                this.videoEventListeners.forEach(({ event, listener }) => {
                    this.videoElement.removeEventListener(event, listener);
                });
            }

            // 定义新的监听器
            this.videoEventListeners = [
                { event: 'play', listener: () => this.sendVideoStatus() },
                { event: 'pause', listener: () => this.sendVideoStatus() },
                { event: 'seeked', listener: () => this.sendVideoStatus() },
                { event: 'ratechange', listener: () => this.sendVideoStatus() },
                { event: 'loadedmetadata', listener: () => this.sendVideoStatus() }
            ];

            // 添加监听器
            this.videoEventListeners.forEach(({ event, listener }) => {
                this.videoElement.addEventListener(event, listener);
            });
        }

        // 发送视频状态
        sendVideoStatus() {
            if (!this.socket || this.socket.readyState !== WebSocket.OPEN) return;

            // 确保有视频元素
            const video = this.findVideoElement();
            if (!video) return;

            const syncData = {
                type: 'sync_video',
                roomId: this.roomId,
                videoInfo: {
                    src: video.src || video.currentSrc,
                    currentTime: video.currentTime || 0,
                    paused: video.paused,
                    playbackRate: video.playbackRate
                }
            };

            this.socket.send(JSON.stringify(syncData));
        }

        // 请求当前视频状态
        requestCurrentVideoStatus() {
            if (!this.socket || this.socket.readyState !== WebSocket.OPEN) return;

            this.socket.send(JSON.stringify({
                type: 'request_video_status',
                roomId: this.roomId
            }));
        }

        // 应用接收到的视频状态
        applyReceivedVideoStatus(data) {
            const { videoInfo } = data;

            // 如果没有视频信息，直接返回
            if (!videoInfo || !videoInfo.src) return;

            // 查找或创建视频元素
            let video = this.findVideoElement();

            // 如果没有视频元素，尝试创建
            if (!video) {
                video = document.createElement('video');
                video.style.width = '100%';
                document.body.appendChild(video);
            }

            // 设置视频源
            if (video.src !== videoInfo.src) {
                video.src = videoInfo.src;
            }

            // 同步播放状态
            video.currentTime = videoInfo.currentTime;

            if (videoInfo.paused) {
                video.pause();
            } else {
                video.play();
            }

            // 设置播放速率
            video.playbackRate = videoInfo.playbackRate;

            this.videoElement = video;
            this.attachVideoListeners();
        }

        // 同步视频
        syncVideo(data) {
            // 如果不是房主，同步视频
            if (!this.isHost) {
                this.applyReceivedVideoStatus(data);
            }
        }

        // 房间加入处理
        onRoomJoined(data) {
            const roomStatus = document.getElementById('roomStatus');
            this.modalOverlay.style.display = 'none';

            roomStatus.textContent = `已成功${this.isHost ? '创建' : '加入'}房间：${this.roomId}`;

            // 如果是房主，设置视频追踪
            if (this.isHost) {
                this.setupHostVideoTracking();
            }
        }

        // 错误处理
        handleError(message) {
            const roomStatus = document.getElementById('roomStatus');
            roomStatus.textContent = `发生错误：${message}`;
        }

        // 生成随机房间ID
        generateRoomId() {
            return Math.random().toString(36).substring(2, 8).toUpperCase();
        }

        // 清理方法
        cleanup() {
            // 清除视频事件监听器
            if (this.videoEventListeners) {
                this.videoEventListeners.forEach(({ event, listener }) => {
                    if (this.videoElement) {
                        this.videoElement.removeEventListener(event, listener);
                    }
                });
            }

            // 清除定时器
            if (this.hostVideoCheckInterval) {
                clearInterval(this.hostVideoCheckInterval);
            }

            // 关闭WebSocket连接
            if (this.socket) {
                this.socket.close();
            }
        }
    }

    // 将TogetherWatch挂载到window对象
    window.TogetherWatch = TogetherWatch;
})(window);

// 使用示例
document.addEventListener('DOMContentLoaded', () => {
    const togetherWatch = new TogetherWatch({
        wsServer: 'ws://localhost:8080' // 替换为您的WebSocket服务器地址
    });
});